#include <func.h>

int main(int argc, char* argv[])
{
	int fd = open("a.txt", O_RDWR);
	if (fd == -1) {
		error(1, errno, "open a.txt");
	}
	
	lseek(fd, 0, SEEK_END);

	// idiom 
	pid_t pid = fork();
	switch (pid) {
	case -1:	// 失败
		error(1, errno, "fork");
	case 0:		// 子进程
		printf("Child: offset = %ld\n", lseek(fd, 0, SEEK_CUR));
		write(fd, "Hello kitty\n", 12);
		close(STDERR_FILENO);
		sleep(3);
		printf("Child: terminated\n");
		exit(0);

	default:	// 父进程
		printf("Parent: offset = %ld\n", lseek(fd, 0, SEEK_CUR));
		sleep(2);
		printf("Parent: offset = %ld\n", lseek(fd, 0, SEEK_CUR));
		int newfd = dup(fd);
		printf("newfd = %d\n", newfd);
		sleep(2);
		printf("Parent: terminated\n");
		exit(0);
	}

    return 0;
}

